package org.yang.common.i18n.config;

import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.yang.common.i18n.resolver.I18nResolver;

import java.util.Properties;

/**
 * 国际化配置
 *
 * @author: lslands
 * @version: 1.0
 * @create: 2024/5/10
 * @description:
 */
@PropertySource(value = "classpath:config/application.properties")

@Slf4j
@Component
public class LocaleConfig implements WebMvcConfigurer {

    @Autowired
    private MessageSource messageSource;


    /**
     *	默认解析器 其中locale表示默认语言,当请求中未包含语种信息，则设置默认语种
     *	当前默认为简体中文,zh_CN
     */
//    @Bean
//    public SessionLocaleResolver sessionLocaleResolver() {
//        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
//        localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
//        return localeResolver;
//    }

    @Bean
    public LocaleResolver localeResolver(){
        return new I18nResolver();
    }

    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    /**
     *  默认拦截器
     *  拦截请求，获取请求头中包含的语种信息并重新注册语种信息
     */
    @Bean
    public WebMvcConfigurer localeInterceptor() {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
//                registry.addInterceptor(new LocaleInterceptor());
                registry.addInterceptor(localeChangeInterceptor());
            }
        };
    }




    @Bean
    public Validator validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        // 设置上方配置的国际化源
        factoryBean.setValidationMessageSource(messageSource);
        // 设置使用 HibernateValidator 校验器
        factoryBean.setProviderClass(HibernateValidator.class);
        Properties properties = new Properties();
        // 设置 快速异常返回
        properties.setProperty("i18n翻译异常", "true");
        factoryBean.setValidationProperties(properties);
        // 加载配置
        factoryBean.afterPropertiesSet();
        return factoryBean.getValidator();
    }
}
